package com.jdk.demo.thread.stampedLock;

import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.StampedLock;

/**
 * StampedLock本身是为了优化ReentrantReadWriteLock的性能，其用法完全跟后者保持一致，可以借用后者的测试用例，如下：
 *
 * @author HP
 *
 */
public class StampedLockTest2 {

	public static void main(String[] args) throws Exception {
		StampedLock lock = new StampedLock();
		Lock readLock = lock.asReadLock();
		CyclicBarrier cyclicBarrier = new CyclicBarrier(6);
		Runnable a = new Runnable() {
			@Override
			public void run() {
				System.out.println(Thread.currentThread().getName() + " start,time->" + System.currentTimeMillis());
				try {
					readLock.lock();
					Thread.sleep(1000);
					System.out.println("do something end for read,time->" + System.currentTimeMillis());
					//cyclicBarrier.await();
				} catch (Exception e) {
					e.printStackTrace();
				} finally {
					readLock.unlock();
				}

			}
		};
		for (int i = 0; i < 3; i++) {
			new Thread(a).start();
		}
		long start = System.currentTimeMillis();
		//cyclicBarrier.await();
		System.out.println("read end,time->" + (System.currentTimeMillis() - start));
		Lock writeLock = lock.asWriteLock();
		Runnable b = new Runnable() {
			@Override
			public void run() {
				System.out.println(Thread.currentThread().getName() + " start,time->" + System.currentTimeMillis());
				try {
					writeLock.lock();
					Thread.sleep(1000);
					System.out.println("do something end for write,time->" + System.currentTimeMillis());
				} catch (Exception e) {
					e.printStackTrace();
				} finally {
					writeLock.unlock();
					try {
						cyclicBarrier.await();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}

			}
		};
		for (int i = 0; i < 1; i++) {
			new Thread(b).start();
		}
		start = System.currentTimeMillis();
		cyclicBarrier.await();
		System.out.println("write end,time->" + (System.currentTimeMillis() - start));
	}

}
